<?php

namespace common\logics;

use Yii;
use common\base\Model;
use common\helpers\StringHelper;
use mpend\models\User;
use common\validators\MobileValidator;
use common\helpers\ConnerTestHelper;

/**
 * 短信验证码发送模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SmsCaptchaForm extends Model {

    use \common\traits\Constants;

    const TPL_AUTH_CODE = 'SMS_150181940';
    //
    const SCOPE_LOGIN = 'login';
    const SCOPE_REGISTER = 'register';
    const SCOPE_FORGET = 'forget';
    const SCOPE_SIGNIN = 'signin';
    const SCOPE_BIND = 'bind';
    const SCOPE_PUBLISH = 'publish';
    const SCOPE_ACCOUNT = 'account';
    //
    const LIMIT_SEND_TIMES = 500;
    const AUTO_FLUSH_DURATION = 86400;
    const CAPTCHA_EXPIRE_TIME = 600;
    const SEND_PERIOD_TIME = 60;

    public $scope;
    public $mobile;
    public $encode = true;
    //
    private $_sendtimes = 0;
    private $_phoneNumber;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'scope'], 'required'],
            ['scope', 'in', 'range' => static::getAttributeMark('scope'), 'message' => '{attribute}不在允许的列表内'],
            ['mobile', 'validateMobile'],
            ['scope', 'validateSendscope'],
            ['mobile', 'validateSendRateLimit'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'mobile' => '手机号',
            'scope' => '标识范围',
        ];
    }

    /**
     * Validates the mobile.
     * @param string $attribute the attribute currently being validated
     */
    public function validateMobile($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if ($this->encode) {
            $encryptMobile = $this->$attribute;
            $mobile = $this->security()->decryptDataByKey($encryptMobile);
        } else {
            $mobile = $this->$attribute;
        }
        if (!$mobile) {
            return $this->addError($attribute, '手机号信息获取失败');
        }
        $validator = new MobileValidator();
        if (!$validator->validate($mobile)) {
            return $this->addError($attribute, '手机号格式不正确');
        }
        $this->_phoneNumber = $mobile;
    }

    /**
     * Validates the password.
     * @param string $attribute the attribute currently being validated
     */
    public function validateSendscope($attribute) {
        if ($this->hasErrors() || $this->$attribute == self::SCOPE_PUBLISH) {
            return;
        }
        $mobile = $this->getPhoneNumber();
        $entryMobile = Yii::$app->security->generatePrivateKey($mobile);
        $exists = User::find()->where(['mobile' => $entryMobile])->exists();
        if ($this->$attribute == self::SCOPE_SIGNIN) {
            if ($exists) {
                $this->$attribute = self::SCOPE_LOGIN;
            } else {
                $this->$attribute = self::SCOPE_REGISTER;
            }
        } else if ($this->$attribute == self::SCOPE_REGISTER || $this->$attribute == self::SCOPE_BIND) {
            if ($exists) {
                $this->addError($attribute, '当前手机号已被占用');
            }
        } else {
            if (!$exists) {
                $this->addError($attribute, '当前手机号未注册帐号');
            }
        }
    }

    /**
     * Validates the SendRateLimit.
     * @param string $attribute the attribute currently being validated
     */
    public function validateSendRateLimit($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $mobile = $this->getPhoneNumber();
        if ($this->sendTimes >= static::LIMIT_SEND_TIMES) {
            $this->addError($attribute, '超过了短信发送的限制次数，24小时之内将屏蔽当前手机号的短信发送。');
        }
        $cache = $this->getCommonCache();
        $period = $cache->get('period_' . $this->scope . '_' . $mobile);
        if ($period) {
            $waitsecond = $period + static::SEND_PERIOD_TIME - time();
            if ($waitsecond > 0) {
                $this->addError($attribute, '重发倒计时剩余：' . $waitsecond . '秒');
            }
        }
    }

    /**
     * 获取手机号
     */
    public function getPhoneNumber() {
        return $this->_phoneNumber;
    }

    /**
     * 获取发送次数
     */
    public function getSendTimes() {
        $mobile = $this->getPhoneNumber();
        $cache = $this->getCommonCache();
        $sendtimes = $cache->get('sendtimes_' . $this->scope . '_' . $mobile);
        if ($sendtimes) {
            $this->_sendtimes = $sendtimes;
        }
        return $this->_sendtimes;
    }

    /**
     * 发送短信校验码
     * @return User|null the saved model or null if saving fails
     */
    public function send() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
        }
        $mobile = $this->getPhoneNumber();
        $captcha = $this->generateCaptcha();
        //提交短信发送
        $status = Yii::$app->dysms->sendSms($mobile, static::TPL_AUTH_CODE, [
            'code' => $captcha,
        ]);
        $data = [
            'send_status' => true,
//            'receive_mobile' => $mobile,
            'scope_times' => $this->_sendtimes,
            'duration' => static::SEND_PERIOD_TIME,
            'message' => '发送成功',
        ];
        if ($status !== true) {
            $data['send_status'] = false;
            $data['message'] = $status;
        } else {
            $cache = $this->getCommonCache();
            $cache->set('period_' . $this->scope . '_' . $mobile, time(), static::SEND_PERIOD_TIME);
            $cache->set('sendtimes_' . $this->scope . '_' . $mobile, $this->_sendtimes + 1, static::AUTO_FLUSH_DURATION);
            $data['scope_times'] += 1;
            if (YII_ENV_DEV || YII_DEBUG) {
                $data['captcha'] = $captcha;
            }
        }

        return $data;
    }

    public function checkEnv() {
        if (ConnerTestHelper::isInner()) {
            return false;
        }
        if (!YII_DEBUG && YII_ENV_PROD) {
            return true;
        }
        return false;
    }

    /**
     * 生成短信校验码
     * @return string
     */
    protected function generateCaptcha() {
        $length = 4;
        if ($this->scope == static::SCOPE_FORGET || $this->scope == static::SCOPE_BIND) {
            $length = 6;
        }
        $mobile = $this->getPhoneNumber();
        $captcha = $this->checkEnv() ? StringHelper::random($length, true) : str_pad('8', $length, '8');
        $cache = $this->getCommonCache();
        $cache->set('captcha_' . $this->scope . '_' . $mobile, $captcha, static::CAPTCHA_EXPIRE_TIME);
        return $captcha;
    }

}
